<template>
  <div class="app-container">
    <div class="custom_card" ref="custom_card">
      <!-- 添加或修改参数配置对话框 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :sm="24" :md="12"  :lg="12">
            <el-form-item label="司机名称" prop="userName">
              <el-input
                v-model="form.userName"
                placeholder="请输入司机名称"
                maxlength="30"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12" :lg="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择归属部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24" :md="12" :lg="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="form.phonenumber"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12" :lg="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24" :md="12" :lg="12">
            <el-form-item
              v-if="form.userId == undefined"
              label="司机密码"
              prop="password1"
            >
              <el-input
                v-model="form.password1"
                placeholder="请输入司机密码"
                type="text"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12" :lg="12">
            <el-form-item label="角色" prop="roleId">
              <el-select
                v-model="form.roleId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :sm="24" :md="12" :lg="12" v-if="qyEnable">
            <el-form-item label="企微账号" prop="qwUserName">
              <el-input v-model="form.qwUserName" placeholder="关联企微账号" readonly>
                <el-button icon="el-icon-search" slot="append" @click="getUserNameByMobile(1)"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12" :lg="12" v-if="ddEnable">
            <el-form-item label="钉钉账号" prop="ddUserName">
              <el-input v-model="form.ddUserName" placeholder="关联钉钉账号"  readonly>
                <el-button icon="el-icon-search" slot="append" @click="getUserNameByMobile(2)"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :sm="24" :md="12" :lg="12">
            <el-form-item label="司机性别">
              <el-select
                v-model="form.sex"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12" :lg="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        <el-col :sm="24" :md="12" :lg="12">
          <el-form-item label="司机类型">
            <el-radio-group v-model="form.driverType">
              <el-radio
                v-for="dict in dict.type.sys_driver_type"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24" :md="12" :lg="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getUser, addUser, updateUser,getDepartmentMembers,getbymobile,getNotifyConfig } from '@/api/system/user'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'User',
  dicts: ['sys_normal_disable', 'sys_user_sex','sys_driver_type'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: true,
      // 部门名称
      deptName: undefined,
      // 默认密码
      /* initPassword: 123456,*/
      // 角色选项
      roleOptions: [],
      //企业微信通讯录
      qyEnable: false,
      ddEnable: false,
      qwUserOptions: [],
      // 表单参数
      form: {
        status: '0',
        driverType: '1',
      },
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '用户名称长度必须介于 2 和 20 之间',
            trigger: 'blur',
          },
        ],
        nickName: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' },
        ],
        password1: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          {
            min: 5,
            max: 20,
            message: '用户密码长度必须介于 5 和 20 之间',
            trigger: 'blur',
          },
        ],
        email: [
          {
            type: 'email',
            message: "'请输入正确的邮箱地址",
            trigger: ['blur', 'change'],
          },
        ],
        phonenumber: [
          { required: true, message: '用户手机不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
        deptId: [
          { required: true, message: '归属部门不能为空', trigger: 'blur' },
        ],
        roleId: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
      },
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    },
  },
  created() {
    this.getTreeselect()
    /* this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });*/
    const userId = this.$route.params && this.$route.params.userId
    if (userId) {
      getUser(userId).then((response) => {
        this.form = response.data
        this.roleOptions = response.roles
        this.form.postIds = response.postIds || []
        this.form.roleId = response.roleId
        this.form.password1 = response.password
      })
    } else {
      getUser().then((response) => {
        this.roleOptions = response.roles
        /*  this.form.password = this.initPassword;*/
      })
    }


    getNotifyConfig().then((res)=>{
      this.qyEnable = res.data.qyEnable
      this.ddEnable = res.data.ddEnable
    })

  },
  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data
      })
    },
    getUserNameByMobile(type) {
      var test = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
      if(this.form.phonenumber&&test.test(this.form.phonenumber)){
        const loading = this.$loading({
          target: this.$refs.custom_card,
          lock: true,
          text: '查询中,请稍等...',
          spinner: 'el-icon-loading',
        });
        getbymobile({type:type,mobile:this.form.phonenumber}).then((response) => {
          let user = response.data
          if(type==1){
            this.$set(this.form, 'qwUserId', user.userid);
            this.$set(this.form, 'qwUserName', user.name);
          }else{
            this.$set(this.form, 'ddUserId', user.userid);
            this.$set(this.form, 'ddUserName', user.name);
          }
        }).finally(e=>{
          loading.close();
        })
      }else {
        this.$modal.msgError('请输入正确的手机号码')
      }
    },
    // 取消按钮
    cancel() {
      this.goBack()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        driverType: '1',
        status: '0',
        remark: undefined,
        postIds: [],
        roleId: undefined,
        qwUserId: undefined,
        qwUserName: undefined,
        ddUserId: undefined,
        ddUserName: undefined,
      }
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.password = this.form.password1
          this.form.isDriver = 1
          this.form.roleIds = []
          this.form.roleIds.push(this.form.roleId)
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.goBack()
            })
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.goBack()
            })
          }
        }
      })
    },
    goBack() {
      this.reset()
      this.$store.commit('app/SET_MMVREF')
      this.$router.go(-1) // 返回
      //关闭子页面
      this.$store.state.tagsView.visitedViews.splice(
        this.$store.state.tagsView.visitedViews.findIndex(
          (item) => item.path === this.$route.path
        ),
        1
      )
      this.$router.push(
        this.$store.state.tagsView.visitedViews[
          this.$store.state.tagsView.visitedViews.length - 1
        ].path
      )
      this.$destroy()
    },
  },
}
</script>
